/**
 * Alipay.com Inc.
 * Copyright (c) 2004-2012 All Rights Reserved.
 */
package com.pingan.mobilegw.adapterservice.model;

import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.springframework.util.CollectionUtils;

import java.io.Serializable;
import java.util.Collection;
import java.util.HashSet;

/**
 * 覆写ToString方法
 * 
 * <li>ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE)
 * 
 * @author jiadao
 * @version $Id: ToString.java, v 0.1 2012-10-30 下午12:21:54 jiadao Exp $
 */
public abstract class ToString implements Serializable {

    /** serialVersionUID */
    private static final long               serialVersionUID = -5650993553286208753L;

    /** 过滤打印filed字段 */
    private static final Collection<String> fieldNames       = new HashSet<String>();

    /** 过滤打印filed字段-通用版本 */
    private static final Collection<String> CommonFieldNames = new HashSet<String>() {
                                                                 /** 序列ID */
                                                                 private static final long serialVersionUID = -6921910846540932113L;

                                                                 {
                                                                     add("userInfo");
                                                                 }
                                                             };

    @Override
    public String toString() {
        return toString(this);
    }

    /**
     * 过滤字段输出
     * 
     * @param o
     * @return
     */
    public static String toString(Object o) {
        if (CollectionUtils.isEmpty(fieldNames)) {
            return ToStringBuilder.reflectionToString(o, ToStringStyle.SHORT_PREFIX_STYLE);
        } else {
            return new ReflectionToStringBuilder(o, ToStringStyle.SHORT_PREFIX_STYLE)
                .setExcludeFieldNames(fieldNames.toArray(new String[fieldNames.size()])).toString();
        }
    }

    /**
     * 添加过滤字段
     * 
     * @param fieldName
     */
    public static void addFilterField(String fieldName) {
        fieldNames.add(fieldName);
    }

    /**
     * 过滤字段输出2
     * 
     * @param o
     * @return
     */
    public static String toLogString(Object o) {
        try {

            if (CollectionUtils.isEmpty(CommonFieldNames)) {
                return ToStringBuilder.reflectionToString(o, ToStringStyle.SHORT_PREFIX_STYLE);
            } else {
                return new ReflectionToStringBuilder(o, ToStringStyle.SHORT_PREFIX_STYLE)
                    .setExcludeFieldNames(
                        CommonFieldNames.toArray(new String[CommonFieldNames.size()])).toString();
            }
        } catch (Exception ex) {
            return null;
        }
    }

}
